/**
 * 
 */
package org.gov.vis.master.gui.listener;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.ResourceBundle;

import javax.swing.JOptionPane;

import org.gov.vis.common.exceptions.InvalidInputException;
import org.gov.vis.gui.util.ErrorsDisplayJPanel;
import org.gov.vis.main.Main;
import org.gov.vis.master.controller.DepartmentCtlr;
import org.gov.vis.master.controller.DepartmentCtlrImpl;
import org.gov.vis.master.dto.DeptDto;
import org.gov.vis.master.gui.EditDepartmentDialog;
import org.gov.vis.master.gui.ViewDepartmentDialog;
import org.gov.vis.util.GuiConstants;
import org.gov.vis.util.Util;

/**
 * @author user
 *
 */
public class EditDepartmentListener implements ActionListener,BaseListener{


	final private ResourceBundle rb = Util.getResources();

	private DepartmentCtlr departmentCtlr = new DepartmentCtlrImpl();

	private EditDepartmentDialog editDepartmentDialog;

	private ErrorsDisplayJPanel errorMsgPanel;
	private DeptDto departmentDto;
	public EditDepartmentListener(EditDepartmentDialog editDepartmentDialog) {
		// TODO Auto-generated constructor stub
		this.editDepartmentDialog = editDepartmentDialog;
	}

	@Override
	public void clear() {
		// TODO Auto-generated method stub

	}

	@Override
	public void setGuiDetailsToDto(Object _guiObject) {
		EditDepartmentDialog _editDepartmentDialog =(EditDepartmentDialog)_guiObject;
		departmentDto = new DeptDto();
		departmentDto.setCode(_editDepartmentDialog.getTxtFldCode().getText());
		departmentDto.setDistrict(_editDepartmentDialog.getTxtFldDistrict().getText());
		departmentDto.setInstitution(_editDepartmentDialog.getTxtFldNameOfInst().getText());
		departmentDto.setMandal(_editDepartmentDialog.getTxtFldManadal().getText());
		departmentDto.setVillage(_editDepartmentDialog.getTxtFldVillage().getText());
		departmentDto.setDeptId((Long)_editDepartmentDialog.getHidnObject());


	}

	@Override
	public void setDtoDetailsToGui(Object _dtoObject) {
		// TODO Auto-generated method stub

	}

	@Override
	public void clearGUILabelColors(Color _labelColor) {
		// TODO Auto-generated method stub

	}

	@Override
	public void actionPerformed(ActionEvent actionEvent) {

		errorMsgPanel = new ErrorsDisplayJPanel(editDepartmentDialog.getjPanel1());
		errorMsgPanel.clearMsgPanel();


		if(actionEvent.getActionCommand().equals(rb.getString("dialog_button_update"))){

			//Method called to either Add or Edit the Department details
			addOrEditDepartment();
		}

		if(actionEvent.getActionCommand().equals(rb.getString("dialog_button_delete"))){
			
			int response = JOptionPane.showConfirmDialog(null, GuiConstants.DELETE_CONFIRM_MSG, "Confirm",
			        JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
			    
		    if (response == JOptionPane.YES_OPTION) {
		      // User clicked YES.
		    	deleteDepartment(actionEvent);
		    	String searchText = editDepartmentDialog.getSearchText();

				// It is basically doing back button functionality. Please, understand the logic and write the comments.
				//Replace double quotes with appropriate Dialog title.
				ViewDepartmentDialog viewDeptDialog = new ViewDepartmentDialog(Main.getMainFrame(), "View Department", false);
				for(ActionListener actionListener: viewDeptDialog.getSearchBtn().getActionListeners()) { 
					ViewDepartmentListener viewDeptList = (ViewDepartmentListener)actionListener;
					viewDeptDialog.getCodeTxtBx().setText(searchText);

					viewDeptList.actionPerformed(new ActionEvent(viewDeptDialog.getSearchBtn(), 1, rb.getString("dialog_button_serach")));
				}

		    	
		    } else if (response == JOptionPane.NO_OPTION || response == JOptionPane.CLOSED_OPTION) {
		      return;
		    }

		}
	}

	private void addOrEditDepartment() {

		//Method called to set the Field's Labels to default Black color
		clearGUILabelColors(blackColor);

		//Method to set the Screen's data to  the DTO Object
		setGuiDetailsToDto(editDepartmentDialog);

		try{
			//Method called to Add or Edit the Department
			departmentCtlr.addOrEditDepartment(departmentDto);
			JOptionPane.showMessageDialog(editDepartmentDialog, rb.getString(GuiConstants.MASTER_EDIT_DEPARTMENT_SUCCESS));
			editDepartmentDialog.dispose();
			Thread.sleep(GuiConstants.THREAD_SLEEP_TIME);

			String searchText = editDepartmentDialog.getSearchText();

			// It is basically doing back button functionality. Please, understand the logic and write the comments.
			//Replace double quotes with appropriate Dialog title.
			ViewDepartmentDialog viewDeptDialog = new ViewDepartmentDialog(Main.getMainFrame(), "View Department", false);
			for(ActionListener actionListener: viewDeptDialog.getSearchBtn().getActionListeners()) { 
				ViewDepartmentListener viewDeptList = (ViewDepartmentListener)actionListener;
				viewDeptDialog.getCodeTxtBx().setText(searchText);

				viewDeptList.actionPerformed(new ActionEvent(viewDeptDialog.getSearchBtn(), 1, rb.getString("dialog_button_serach")));
			}

		}catch(Exception e){
			List<String> errorMsgLst = new ArrayList<String>();
			if(e instanceof InvalidInputException){
				final HashMap<String,String> _exceptions = DepartmentCtlr.errorMsgs;
				if (_exceptions != null && !_exceptions.isEmpty()) {
					String errMsg = null;

					if(_exceptions.containsKey(rb.getString("dialog_label_dept_code").toUpperCase())){
						editDepartmentDialog.getLblCode().setForeground(redColor);
						errMsg = _exceptions.remove(rb.getString("dialog_label_dept_code").toUpperCase());
						errorMsgLst.add(errMsg);
					}

					if(_exceptions.containsKey(rb.getString("dialog_label_dept_institution").toUpperCase())){
						editDepartmentDialog.getLblNameOfInst().setForeground(redColor);
						errMsg = _exceptions.remove(rb.getString("dialog_label_dept_institution").toUpperCase());
						errorMsgLst.add(errMsg);
					}
					errorMsgPanel.setErrorMessages(errorMsgLst);
				} else {
					//log.debug(e.getMessage(), e);
				}	
			}else{
				errorMsgLst.add(e.getMessage());
				errorMsgPanel.setErrorMessages(errorMsgLst);

			}
		}

	}

	private void deleteDepartment(ActionEvent actionEvent) {

		Long departmentsId = (Long)editDepartmentDialog.getHidnObject();
		try {
			departmentCtlr.deleteDepartment(departmentsId);
			JOptionPane.showMessageDialog(editDepartmentDialog, rb.getString(GuiConstants.MASTER_DELETE_DEPARTMENT_SUCCESS));
			editDepartmentDialog.dispose();
		} catch (Exception e) {
			List<String> errorMsgLst = new ArrayList<String>();
			errorMsgLst.add(e.getMessage());
			errorMsgPanel.setErrorMessages(errorMsgLst);

		}
	}




}
